package pers.vic.system.system.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import pers.vic.base.bo.system.SysMenu;
import pers.vic.base.vo.AuthorityData;
import pers.vic.system.system.mapper.SysMenuMapper;
import pers.vic.system.system.mapper.SysRoleMapper;
import pers.vic.util.CommonUtils;

/**
 * 权限service
 * 
 * @author VIC
 *
 */
@Service
public class AuthorityService {

	@Resource
	private SysMenuMapper sysMenuMapper;
	
	@Resource
	private SysRoleMapper sysRoleMapper;

	/**
	 * 当前角色拥有的权限列表
	 */
	public List<SysMenu> authorityTree(int roleId) {

		return sysMenuMapper.authorityTree(roleId);
	}
	
	


	/**
	 * 保存用户的权限
	 */
	public void saveAuthority(int roleId, String menuIds) {
		// 存在的就不在建立 不存在的就建立 另外的则删除

		//构建角色和菜单的关系
		if (StringUtils.isNotBlank(menuIds) && menuIds.matches("(\\d|\\d+,|\\d+,\\d+)+")) {
			AuthorityData menuAuthorityData = AuthorityData.instance(getRoleMenuIds(roleId),
					CommonUtils.toIntList(menuIds.split(",")));
			// 新建角色和菜单关系
			if (!menuAuthorityData.getNeedAdd().isEmpty()) {
				sysRoleMapper.addRoleMenu(roleId, menuAuthorityData.getNeedAdd());
			}

			// 删除角色菜单关系
			if (!menuAuthorityData.getNeedDelete().isEmpty()) {
				sysRoleMapper.deleteRoleMenu(roleId, menuAuthorityData.getNeedDelete());
			}
		} else {// 删除角色和菜单的关系
			sysRoleMapper.deleteRoleMenuByRoleId(roleId);
		}
	}




	private List<Integer> getRoleMenuIds(int roleId) {
		return sysMenuMapper.getRoleMenuIds(roleId);
	}

}
